package com.hnyfkj.jyindustry.common.oauth2;

import com.hnyfkj.jyindustry.common.constant.Constant;
import com.hnyfkj.jyindustry.common.exception.HnyfkjBusinessException;
import com.hnyfkj.jyindustry.common.utils.JsonUtil;
import com.hnyfkj.jyindustry.common.utils.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: jyindustry
 * @description:oauth2 filter类
 * @author: zl
 * @create: 2020-07-09 18:05
 **/
public class OAuth2Filter extends AuthenticatingFilter {

	@Override
	protected AuthenticationToken createToken(final ServletRequest request, final ServletResponse response)
			throws Exception {
		// 获取请求token
		final String token = getRequestToken((HttpServletRequest) request);

		if (StringUtils.isBlank(token)) {
			return null;
		}

		return new OAuth2Token(token);
	}

	@Override
	protected boolean isAccessAllowed(final ServletRequest request, final ServletResponse response,
                                      final Object mappedValue) {
		return false;
	}

	@Override
	protected boolean onAccessDenied(final ServletRequest request, final ServletResponse response) throws Exception {
		// 获取请求token，如果token不存在，直接返回401
		final String token = getRequestToken((HttpServletRequest) request);
		if (StringUtils.isBlank(token)) {

			final HttpServletResponse httpResponse = (HttpServletResponse) response;
			final String json = JsonUtil.toString(new HnyfkjBusinessException("invalid token", Constant.NOT_LOGIN_CODE));
			httpResponse.getWriter().print(json);
			httpResponse.setStatus(Constant.NOT_LOGIN_CODE);

			return false;
		}

		if (ShiroUtils.isLogin()) {
			// 查看是否已登录
			return true;
		} else {
			// 如果未登录，再登录次试试
			return executeLogin(request, response);
		}

	}

	@Override
	protected boolean onLoginFailure(final AuthenticationToken token, final AuthenticationException e,
                                     final ServletRequest request, final ServletResponse response) {
		final HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setContentType("application/json;charset=utf-8");

		try {
			// 处理登录失败的异常
			final Throwable throwable = e.getCause() == null ? e : e.getCause();
			final String json = JsonUtil.toString(new HnyfkjBusinessException(throwable.getMessage(), Constant.NOT_LOGIN_CODE));
			httpResponse.getWriter().print(json);
			httpResponse.setStatus(Constant.NOT_LOGIN_CODE);
		} catch (final IOException e1) {

		}

		return false;
	}

	/**
	 * 获取请求的token
	 */
	private String getRequestToken(final HttpServletRequest httpRequest) {
		// 从header中获取token
		String token = httpRequest.getHeader(Constant.HEADER_TOKEN);

		// 如果header中不存在token，则从参数中获取token
		if (StringUtils.isBlank(token)) {
			token = httpRequest.getParameter(Constant.HEADER_TOKEN);
		}

		return token;
	}

}
